import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import {
  Alert,
  Row,
  Col,
  Button,
  Form,
  Input,
  InputNumber,
  Select,
  Tag,
  Modal,
  message,
  Space,
} from 'antd';
import {
  MenuOutlined,
  SwapOutlined,
  ReadOutlined,
  AppstoreAddOutlined,
  PlusOutlined,
  ArrowDownOutlined,
  ArrowUpOutlined,
  SketchOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  InfoCircleOutlined,
  FolderOpenOutlined,
  RightOutlined,
  BookOutlined, 
  PlusSquareOutlined, 
} from '@ant-design/icons';
import * as XLSX from 'xlsx';
import { setStrategyType, getStrategyType } from '@/utils/keyTypeStore';
import './index.scss'



const globalDOMTrackStats = { created: 0, destroyed: 0, reused: 0, reset: () => {
    globalDOMTrackStats.created = 0;
    globalDOMTrackStats.destroyed = 0;
    globalDOMTrackStats.reused = 0;
}};

const useDOMTrack = (id) => {
  const ref = useRef(null);

  useEffect(() => {
    if (ref.current) {
      
      globalDOMTrackStats.created++;
    }
    return () => {
      
      globalDOMTrackStats.destroyed++;
    };
  }, [id]); 
  return ref;
};


const generateCategoryId = () => `cat_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

const createCategory = (name, description = '', bookCount = 0, level = 1) => ({
  id: generateCategoryId(),
  name: name,
  description: description,
  bookCount: bookCount,
  status: 'active',
  level: level,
  createTime: new Date().toISOString(),
  updateTime: new Date().toISOString(),
  children: [],
});

const generateMockBook = (nextIdRef) => {
  const realTitles = [
    '百年孤独', '1984', '动物农场', '小王子', '围城', '活着', '三体', '人类简史', '情商', '影响力',
    '乌合之众', '君主论', '资治通鉴', '红楼梦', '西游记', '水浒传', '三国演义', '呐喊', '朝花夕拾', '边城'
  ];
  const realAuthors = [
    '加西亚·马尔克斯', '乔治·奥威尔', '安托万·德·圣-埃克苏佩里', '钱钟书', '余华', '刘慈欣', '尤瓦尔·赫拉利', '丹尼尔·戈尔曼', '古斯塔夫·勒庞', '尼科洛·马基雅维利',
    '司马光', '曹雪芹', '吴承恩', '施耐庵', '罗贯中', '鲁迅', '沈从文'
  ];
  const realPublishers = [
    '新经典文化', '上海译文出版社', '人民文学出版社', '北京十月文艺出版社', '重庆出版社',
    '中信出版集团', '浙江人民出版社', '商务印书馆', '译林出版社', '南海出版公司'
  ];
  const descriptions = [
    '本书详细介绍了相关技术原理与实践。',
    '适合初学者和进阶开发者阅读。',
    '内容涵盖理论与实战案例。',
    '帮助读者快速掌握核心知识。'
  ];
  return {
    id: nextIdRef.current++,
    title: realTitles[Math.floor(Math.random() * realTitles.length)],
    author: realAuthors[Math.floor(Math.random() * realAuthors.length)],
    status: '在架',
    expanded: false,
    isbn: '978' + Math.floor(1000000000 + Math.random() * 9000000000),
    publisher: realPublishers[Math.floor(Math.random() * realPublishers.length)],
    publishDate: `202${Math.floor(Math.random() * 4 + 1)}-0${Math.floor(Math.random() * 9 + 1)}-15`,
    description: descriptions[Math.floor(Math.random() * descriptions.length)],
    price: (Math.random() * 100 + 20).toFixed(2),
    rating: (Math.random() * 2 + 3).toFixed(1)
  };
};

const NestedList = () => {
  const [categoryTree, setCategoryTree] = useState([]);
  const [loading, setLoading] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [editDialogVisible, setEditDialogVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState(null);
  const [currentCategory, setCurrentCategory] = useState({});
  const [books, setBooks] = useState([]);
  const nextId = useRef(1); 
  const [keyType, setKeyType] = useState(getStrategyType());
  const [renderTime, setRenderTime] = useState(null);
  const [domTrackStats, setDomTrackStats] = useState({ created: 0, destroyed: 0, reused: 0 });
  const [showAcademicTestList, setShowAcademicTestList] = useState(false);
  const [academicBooks, setAcademicBooks] = useState([]);


  const refs = useRef([]);

  
  const handleToggleType = value => {
    message.success({
      content: `已切换到${value}`,
    });
    setKeyType(value);
    setStrategyType(value);
  };

  const totalCategories = useMemo(() => {
    const countNodes = (nodes) => {
      let count = 0;
      nodes.forEach(node => {
        count++;
        if (node.children && node.children.length > 0) {
          count += countNodes(node.children);
        }
      });
      return count;
    };
    return countNodes(categoryTree);
  }, [categoryTree]);

  const maxDepth = useMemo(() => {
    const getMaxDepth = (nodes, currentDepth = 1) => {
      if (!nodes || nodes.length === 0) return 0;
      let maxD = currentDepth;
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          const childDepth = getMaxDepth(node.children, currentDepth + 1);
          maxD = Math.max(maxD, childDepth);
        }
      });
      return maxD;
    };
    return getMaxDepth(categoryTree);
  }, [categoryTree]);

  const totalBooks = useMemo(() => {
    const sumBookCount = (nodes) => {
      let total = 0;
      nodes.forEach(node => {
        total += node.bookCount || 0;
        if (node.children && node.children.length > 0) {
          total += sumBookCount(node.children);
        }
      });
      return total;
    };
    return sumBookCount(categoryTree);
  }, [categoryTree]);

  const reuseRate = useMemo(() => {
    const N = academicBooks.length;
    if (N === 0) return '0.00';

    
    
    
    
    
    
    const reusedCount = N - domTrackStats.destroyed; 
    return (reusedCount >= 0 && N > 0 ? (reusedCount / N) * 100 : 0).toFixed(2);
  }, [academicBooks.length, domTrackStats.destroyed]);


  
  const findCategoryAndOperate = useCallback((nodes, categoryId, operation) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === categoryId) {
        operation(nodes, i);
        return true;
      }
      if (nodes[i].children && nodes[i].children.length > 0) {
        if (findCategoryAndOperate(nodes[i].children, categoryId, operation)) {
          return true;
        }
      }
    }
    return false;
  }, []);

  const addRootCategory = () => {
    const newCategory = createCategory('新根分类', '这是一个新的根分类', 10);
    setCategoryTree(prev => [...prev, newCategory]);
  };

  const addSubCategory = (parentCategory) => {
    const newCategory = createCategory('新子分类', `这是${parentCategory.name}的子分类`, 5, parentCategory.level + 1);
    setCategoryTree(prevTree => {
      const updatedTree = JSON.parse(JSON.stringify(prevTree)); 
      const addOperation = (nodes, index) => {
        if (!nodes[index].children) {
          nodes[index].children = [];
        }
        nodes[index].children.push(newCategory);
      };
      findCategoryAndOperate(updatedTree, parentCategory.id, addOperation);

      if (!expandedKeys.includes(parentCategory.id)) {
        setExpandedKeys(prev => [...prev, parentCategory.id]);
      }
      return updatedTree;
    });
  };

  const editCategory = (category) => {
    setEditingCategory(category);
    setCurrentCategory({ ...category });
    setEditDialogVisible(true);
  };

  const saveCategory = () => {
    if (editingCategory) {
      setCategoryTree(prevTree => {
        const updatedTree = JSON.parse(JSON.stringify(prevTree));
        const updateOperation = (nodes, index) => {
          Object.assign(nodes[index], {
            ...currentCategory,
            updateTime: new Date().toISOString()
          });
        };
        findCategoryAndOperate(updatedTree, editingCategory.id, updateOperation);
        return updatedTree;
      });
    }
    setEditDialogVisible(false);
    setEditingCategory(null);
    message.success('分类已保存！');
  };

  const deleteCategory = (categoryToDelete) => {
    Modal.confirm({
      title: `确定要删除分类"${categoryToDelete.name}"及其所有子分类吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk() {
        setCategoryTree(prevTree => {
          const updatedTree = JSON.parse(JSON.stringify(prevTree));
          const deleteOperation = (nodes, index) => nodes.splice(index, 1);
          findCategoryAndOperate(updatedTree, categoryToDelete.id, deleteOperation);
          return updatedTree;
        });
        message.success('删除成功！');
      },
      onCancel() {
        message.info('已取消删除');
      },
    });
  };

  const generateNestedCategories = (level1Count, minLevel2Children, minLevel3Children) => {
    const categories = [];
    const level1Names = ['文学艺术', '科学技术', '历史地理', '社会科学', '教育培训', '生活时尚', '少儿读物', '经济管理', '医学健康', '哲学宗教', '计算机与互联网', '法律', '军事', '体育', '旅游'];
    const level2Names = ['小说', '诗歌', '散文', '传记', '艺术理论', '绘画', '音乐', '物理学', '化学', '生物学', '数学', '天文学', '地球科学', '中国历史', '世界历史', '地理学', '考古学', '政治学', '经济学', '社会学', '心理学', '管理学', '教育学', '职业技能', '外语学习', '烹饪美食', '健康养生', '时尚穿搭', '家居生活', '童话故事', '儿童文学', '益智游戏', '宏观经济', '微观经济', '金融投资', '市场营销', '中医', '西医', '营养学', '疾病预防', '哲学', '宗教学', '伦理学'];
    const level3Names = ['现代小说', '古典文学', '外国文学', '中国文学', '科幻小说', '推理小说', '唐诗宋词', '现代诗', '中国近现代史', '世界近代史', '古代史', '当代史', 'C++编程', 'Java开发', 'Python数据分析', 'JavaScript前端', '人工智能基础', '机器学习实践', '高等数学', '线性代数', '烹饪技巧', '烘焙入门', '儿童绘本', '睡前故事'];

    for (let i = 0; i < level1Count; i++) {
      const level1 = createCategory(`${level1Names[i % level1Names.length]} - ${i + 1}`, '', Math.floor(Math.random() * 10 + 1), 1);
      for (let j = 0; j < minLevel2Children; j++) {
        const level2 = createCategory(`${level2Names[j % level2Names.length]} - ${i + 1}-${j + 1}`, '', Math.floor(Math.random() * 10 + 1), 2);
        for (let k = 0; k < minLevel3Children; k++) {
          const level3 = createCategory(`${level3Names[k % level3Names.length]} - ${i + 1}-${j + 1}-${k + 1}`, '', Math.floor(Math.random() * 10 + 1), 3);
          level2.children.push(level3);
        }
        level1.children.push(level2);
      }
      categories.push(level1);
    }
    return categories;
  };

  const resetCategories = () => {
    setLoading(true);
    
    setCategoryTree(generateNestedCategories(7, 10, 50));
    setExpandedKeys([]); 
    setLoading(false);
  };

  const toggleExpand = (category) => {
    setExpandedKeys(prevKeys => {
      const index = prevKeys.indexOf(category.id);
      if (index > -1) {
        const newKeys = [...prevKeys];
        newKeys.splice(index, 1);
        return collapseChildren(newKeys, category);
      } else {
        return [...prevKeys, category.id];
      }
    });
  };

  const collapseChildren = (currentKeys, category) => {
    let newKeys = [...currentKeys];
    if (category.children) {
      category.children.forEach(child => {
        const index = newKeys.indexOf(child.id);
        if (index > -1) {
          newKeys.splice(index, 1);
        }
        newKeys = collapseChildren(newKeys, child); 
      });
    }
    return newKeys;
  };

  const isExpanded = (categoryId) => expandedKeys.includes(categoryId);

  const expandAll = () => {
    const allKeys = [];
    const collectKeys = (node) => {
      allKeys.push(node.id);
      if (node.children) {
        node.children.forEach(collectKeys);
      }
    };
    categoryTree.forEach(collectKeys);
    setExpandedKeys(allKeys);
  };

  const collapseAll = () => {
    setExpandedKeys([]);
  };

  const quickDemo = () => {
    message.info('执行快速演示...');
    setLoading(true);
    resetCategories();
    setTimeout(() => {
      addRootCategory();
      setLoading(false);
    }, 500);
  };

  const getStatusType = (status) => {
    switch (status) {
      case 'active': return 'success';
      case 'disabled': return 'error'; 
      default: return 'default';
    }
  };

  const viewCategoryBooks = (category) => {
    message.info(`查看分类 "${category.name}" 下的图书`);
  };

  
  const generateBooks = (count = 10) => {
    nextId.current = 1;
    const arr = Array.from({ length: count }, () => generateMockBook(nextId));
    setBooks(arr);
  };

  const addItem = () => {
    const newItem = generateMockBook(nextId);
    setBooks(prev => {
      const newBooks = [...prev];
      newBooks.splice(Math.floor(newBooks.length / 2), 0, newItem);
      return newBooks;
    });
  };

  const removeItem = () => {
    setBooks(prev => {
      if (prev.length === 0) return prev;
      const newBooks = [...prev];
      const randomIndex = Math.floor(Math.random() * newBooks.length);
      newBooks.splice(randomIndex, 1);
      return newBooks;
    });
  };

  const shuffleList = () => {
    setBooks(prev => {
      const newBooks = [...prev];
      for (let i = newBooks.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newBooks[i], newBooks[j]] = [newBooks[j], newBooks[i]];
      }
      return newBooks;
    });
  };

  const insertRandomBook = () => {
    const newItem = generateMockBook(nextId);
    setBooks(prev => {
      const newBooks = [...prev];
      const idx = Math.floor(Math.random() * (newBooks.length + 1));
      newBooks.splice(idx, 0, newItem);
      return newBooks;
    });
  };

  const deleteRandomBook = () => {
    setBooks(prev => {
      if (prev.length === 0) return prev;
      const newBooks = [...prev];
      const idx = Math.floor(Math.random() * newBooks.length);
      newBooks.splice(idx, 1);
      return newBooks;
    });
  };

  const replaceAllBooks = () => {
    const len = books.length;
    setBooks(Array.from({ length: len }, () => generateMockBook(nextId)));
  };

  const appendToEnd = () => {
    setBooks(prev => [...prev, generateMockBook(nextId)]);
  };

  const stepInsert = () => {
    setBooks(prev => {
      let newBooks = [...prev];
      for (let i = 0; i < 10; i++) {
        newBooks.splice(i * 2, 0, generateMockBook(nextId));
      }
      return newBooks;
    });
  };

  const insertToMiddle = () => {
    setBooks(prev => {
      const newBooks = [...prev];
      const mid = Math.floor(newBooks.length / 2);
      newBooks.splice(mid, 0, generateMockBook(nextId));
      return newBooks;
    });
  };

  const partialUpdate = () => {
    setBooks(prev => {
      if (prev.length === 0) return prev;
      const newBooks = [...prev];
      for (let i = 0; i < 10 && newBooks.length > 0; i++) {
        const idx = Math.floor(Math.random() * newBooks.length);
        newBooks[idx] = { ...newBooks[idx], title: newBooks[idx].title + '_更新' };
      }
      return newBooks;
    });
  };

  
  const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

  const measureOperation = useCallback(async (operationFn) => {
    return new Promise(resolve => {
      requestAnimationFrame(() => {
        performance.clearMarks();
        performance.clearMeasures();
        performance.mark('op-start');

        operationFn();

        
        setTimeout(() => {
          requestAnimationFrame(() => {
            performance.mark('op-end');
            performance.measure('op-duration', 'op-start', 'op-end');
            const measure = performance.getEntriesByName('op-duration')[0];
            const duration = measure ? measure.duration.toFixed(2) : '0.00';
            setRenderTime(duration);
            resolve(duration);
          });
        }, 0); 
      });
    });
  }, []);

  const generateAcademicBooks = (count) => {
    nextId.current = 1; 
    setAcademicBooks(Array.from({ length: count }, () => generateMockBook(nextId)));
  };

  const insertRandomAcademicBook = () => {
    const newItem = generateMockBook(nextId);
    setAcademicBooks(prev => {
      const newBooks = [...prev];
      const randomIndex = Math.floor(Math.random() * (newBooks.length + 1));
      newBooks.splice(randomIndex, 0, newItem);
      return newBooks;
    });
  };

  const deleteRandomAcademicBook = () => {
    setAcademicBooks(prev => {
      if (prev.length === 0) return prev;
      const newBooks = [...prev];
      const randomIndex = Math.floor(Math.random() * newBooks.length);
      newBooks.splice(randomIndex, 1);
      return newBooks;
    });
  };

  const replaceAllAcademicBooks = () => {
    const len = academicBooks.length > 0 ? academicBooks.length : 100;
    setAcademicBooks(Array.from({ length: len }, () => generateMockBook(nextId)));
  };

  const appendToEndAcademicBook = () => {
    setAcademicBooks(prev => [...prev, generateMockBook(nextId)]);
  };

  const insertToMiddleAcademicBook = () => {
    setAcademicBooks(prev => {
      const newBooks = [...prev];
      const mid = Math.floor(newBooks.length / 2);
      newBooks.splice(mid, 0, generateMockBook(nextId));
      return newBooks;
    });
  };

  const partialUpdateAcademicBook = () => {
    setAcademicBooks(prev => {
      if (prev.length === 0) return prev;
      const newBooks = [...prev];
      const numToUpdate = Math.min(10, newBooks.length);
      for (let i = 0; i < numToUpdate; i++) {
        const idx = Math.floor(Math.random() * newBooks.length);
        newBooks[idx] = { ...newBooks[idx], title: newBooks[idx].title + '_更新' };
      }
      return newBooks;
    });
  };

  const shuffleAcademicBooks = () => {
    setAcademicBooks(prev => {
      const newBooks = [...prev];
      for (let i = newBooks.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newBooks[i], newBooks[j]] = [newBooks[j], newBooks[i]];
      }
      return newBooks;
    });
  };

  const performAcademicBookOperationAndMeasure = useCallback(async (keyTypeVal, operationName, operationFn) => {
    console.log(`performAcademicBookOperationAndMeasure: Starting test for KeyType: ${keyTypeVal}, Operation: ${operationName}`);

    setKeyType(keyTypeVal);
    setShowAcademicTestList(true);
    setRenderTime(null);

    
    globalDOMTrackStats.reset();
    setDomTrackStats({ created: 0, destroyed: 0, reused: 0 }); 

    
    setAcademicBooks([]);
    await sleep(50); 

    const totalTimeStart = performance.now();

    
    if (!operationName.startsWith('生成')) {
      generateAcademicBooks(500); 
      await sleep(50); 
      globalDOMTrackStats.reset(); 
      setDomTrackStats({ created: 0, destroyed: 0, reused: 0 });
    }

    const renderDuration = await measureOperation(operationFn);
    const totalTime = (performance.now() - totalTimeStart).toFixed(2);

    setDomTrackStats({
      created: globalDOMTrackStats.created,
      destroyed: globalDOMTrackStats.destroyed,
      reused: academicBooks.length - globalDOMTrackStats.destroyed, 
    });
    const currentAcademicListLength = academicBooks.length;
    const reusedCount = currentAcademicListLength - globalDOMTrackStats.destroyed;
    const reuseRatePercentage = (reusedCount >= 0 && currentAcademicListLength > 0 ? (reusedCount / currentAcademicListLength) * 100 : 0).toFixed(2);

    const result = {
      '测试类型': keyTypeVal,
      '操作类型': operationName,
      '渲染时间(ms)': renderDuration,
      '总耗时(ms)': totalTime,
      'DOM创建数': globalDOMTrackStats.created,
      'DOM复用数': reusedCount,
      'DOM销毁数': globalDOMTrackStats.destroyed,
      'DOM复用率(%)': reuseRatePercentage,
      '列表项数量': currentAcademicListLength,
      '测试时间': new Date().toLocaleString(),
    };
    console.log(`Test Result for ${operationName} (${keyTypeVal}):`, result);
    return result;
  }, [measureOperation, academicBooks]);


  const autoTestReuse = useCallback(async () => {
    console.log('autoTestReuse: Starting test...');
    globalDOMTrackStats.reset();
    setDomTrackStats({ created: 0, destroyed: 0, reused: 0 });
    setShowAcademicTestList(true);

    setAcademicBooks([]); 
    await sleep(100);

    
    generateAcademicBooks(100);
    await sleep(100);
    
    globalDOMTrackStats.reset();

    console.log(`autoTestReuse: Performing operation for keyType: ${keyType}...`);
    const opStart = performance.now();
    if (keyType === 'id') {
      shuffleAcademicBooks();
      console.log('Operation: shuffleAcademicBooks (for ID keys)');
    } else {
      const currentLength = academicBooks.length;
      setAcademicBooks([]); 
      await sleep(200); 
      generateAcademicBooks(currentLength); 
      console.log('Operation: replaceAllBooks (for Index/None keys)');
    }
    const opEnd = performance.now();
    const operationDuration = (opEnd - opStart).toFixed(2);

    await sleep(500); 

    const currentN = academicBooks.length;
    const createdDuringOperation = globalDOMTrackStats.created;
    const destroyedDuringOperation = globalDOMTrackStats.destroyed;

    
    const reusedCalculated = currentN - destroyedDuringOperation;
    const reuseRatePercentageCalculated = (reusedCalculated >= 0 && currentN > 0 ? (reusedCalculated / currentN) * 100 : 0).toFixed(2);

    const stats = {
      created: createdDuringOperation,
      reused: reusedCalculated,
      destroyed: destroyedDuringOperation,
      reuseRate: reuseRatePercentageCalculated,
      totalItems: currentN,
    };

    setDomTrackStats(stats);
    setRenderTime(operationDuration); 
    setShowAcademicTestList(false); 

    console.log('autoTestReuse: Test finished. Stats (for current operation):', stats);
    return stats;
  }, [academicBooks, keyType]); 


  const autoTestBatchAndExportExcel = async () => {
    setLoading(true);
    const testCases = [
      { name: 'ID作为Key', keyType: 'id' },
      { name: 'Index作为Key', keyType: 'index' },
      { name: '无Key', keyType: 'none' }
    ];

    const results = [];
    const operations = [
      { name: '生成100本', fn: (count = 100) => generateAcademicBooks(count), isGenerate: true },
      { name: '生成1000本', fn: (count = 1000) => generateAcademicBooks(count), isGenerate: true },
      { name: '打乱顺序', fn: () => shuffleAcademicBooks(), isGenerate: false },
      { name: '插入元素', fn: () => insertRandomAcademicBook(), isGenerate: false },
      { name: '删除元素', fn: () => deleteRandomAcademicBook(), isGenerate: false },
      { name: '替换所有', fn: () => replaceAllAcademicBooks(), isGenerate: false },
      { name: '尾部追加', fn: () => appendToEndAcademicBook(), isGenerate: false },
      { name: '中间插入', fn: () => insertToMiddleAcademicBook(), isGenerate: false },
      { name: '局部更新', fn: () => partialUpdateAcademicBook(), isGenerate: false }
    ];

    for (const testCase of testCases) {
      message.info(`开始测试: ${testCase.name}`);

      for (const operation of operations) {
        
        const opFn = operation.isGenerate ? () => operation.fn(parseFloat(operation.name.replace('生成', '').replace('本', ''))) : operation.fn;
        const data = await performAcademicBookOperationAndMeasure(testCase.keyType, operation.name, opFn);
        results.push(data);
        await sleep(500); 
      }
    }

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(results);

    const colWidths = [
      { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 },
      { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 20 }
    ];
    ws['!cols'] = colWidths;

    XLSX.utils.book_append_sheet(wb, ws, 'DOM性能测试结果');

    const fileName = `DOM性能测试结果_${new Date().toISOString().slice(0, 19).replace(/[:]/g, '-')}.xlsx`;
    XLSX.writeFile(wb, fileName);

    message.success('测试完成，数据已导出到Excel文件');
    setLoading(false);
  };

  const exportReuseStatsToExcel = () => {
    const stats = [{
      created: globalDOMTrackStats.created,
      reused: academicBooks.length - globalDOMTrackStats.destroyed, 
      destroyed: globalDOMTrackStats.destroyed,
      reuseRate: reuseRate + '%',
      time: new Date().toLocaleString()
    }];

    const ws = XLSX.utils.json_to_sheet(stats);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '复用统计');
    XLSX.writeFile(wb, `reuse-stats-${Date.now()}.xlsx`);
    message.success('统计数据已导出为Excel！');
  };

  
  useEffect(() => {
    resetCategories();
    generateBooks(10);
  }, []); 

  
  const CategoryItem = ({ category }) => {
    const isNodeExpanded = isExpanded(category.id);
    const hasChildren = category.children && category.children.length > 0;

    return (
      <div className="category-item">
        <div className="category-header">
          <div className="category-main">
            {hasChildren ? (
              <RightOutlined
                className={`expand-icon ${isNodeExpanded ? 'expanded' : ''}`}
                onClick={() => toggleExpand(category)}
              />
            ) : (
              <span className="expand-placeholder"></span>
            )}
            <span className="category-name" onClick={() => viewCategoryBooks(category)}>
              {category.name}（{category.bookCount}本）
            </span>
            <Tag color={getStatusType(category.status)} size="small">
              {category.status}
            </Tag>
          </div>
          <div className="category-actions">
            <Button size="small" type="success" icon={<PlusOutlined />} onClick={() => addSubCategory(category)} />
            <Button size="small" type="primary" icon={<EditOutlined />} onClick={() => editCategory(category)} />
            <Button size="small" type="danger" icon={<DeleteOutlined />} onClick={() => deleteCategory(category)} />
          </div>
        </div>

        {isNodeExpanded && hasChildren && (
          <div className="category-children">
            {category.children.map(child => (
              <CategoryItem key={child.id} category={child} />
            ))}
          </div>
        )}
      </div>
    );
  };


  return (
    <div className="nested-list-container">
      <h1 className="page-heading">分类管理系统</h1>
      <div className="description">
        <Alert
          message="模块说明"
          description="分类管理系统用于管理图书馆的图书分类层级结构。支持多级分类创建、编辑、删除、拖拽排序等功能，采用Vue.js Key绑定策略优化树形结构的渲染性能。"
          type="info"
          showIcon
          closable={false}
        />
      </div>

      <div className="statistics-panel">
        <Row gutter={20}>
          <Col span={6}>
            <div className="stat-card">
              <div className="stat-icon categories">
                <MenuOutlined />
              </div>
              <div className="stat-info">
                <h3>{totalCategories}</h3>
                <p>总分类数</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="stat-card">
              <div className="stat-icon levels">
                <SwapOutlined />
              </div>
              <div className="stat-info">
                <h3>{maxDepth}</h3>
                <p>最大层级</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="stat-card">
              <div className="stat-icon books">
                <ReadOutlined />
              </div>
              <div className="stat-info">
                <h3>{totalBooks}</h3>
                <p>图书总数</p>
              </div>
            </div>
          </Col>
          <Col span={6}>
            <div className="stat-card">
              <div className="stat-icon strategy">
                <AppstoreAddOutlined />
              </div>
              <div className="stat-info">
                <h3>{keyType === 'id' ? 'ID作为Key' : keyType === 'index' ? 'Index作为Key' : '无Key'}</h3>
                <p>Key策略</p>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <div className="control-panel">
        <Form layout="inline" className="control-form">
          <Form.Item label="快速操作" className="p-2">
            <Space wrap>
              <Button color="green" variant="solid" onClick={addRootCategory} loading={loading} icon={<PlusOutlined />}>
                添加根分类
              </Button>
              <Button color="blue" variant="solid" onClick={expandAll} loading={loading} icon={<ArrowDownOutlined />}>
                展开全部
              </Button>
              <Button color="orange" variant="solid" onClick={collapseAll} loading={loading} icon={<ArrowUpOutlined />}>
                收起全部
              </Button>
              <Button color="gold" variant="solid" onClick={quickDemo} loading={loading} icon={<SketchOutlined />}>
                快速演示
              </Button>
              <Button color="green" variant="solid" onClick={resetCategories} loading={loading} icon={<ReloadOutlined />}>
                重置数据
              </Button>
            </Space>
          </Form.Item>
          <Form.Item label="图书操作" className="p-2">
            <Space wrap >
              <Button color="green" variant="solid" onClick={() => generateBooks(10)}>生成10本图书</Button>
              <Button color="blue" variant="solid" onClick={addItem}>添加项</Button>
              <Button color="orange" variant="solid" onClick={removeItem}>删除项</Button>
              <Button color="gold" variant="solid" onClick={shuffleList}>打乱顺序</Button>
              <Button color="green" variant="solid" onClick={insertRandomBook}>插入元素</Button>
              <Button color="blue" variant="solid" onClick={deleteRandomBook}>删除元素</Button>
              <Button color="orange" variant="solid" onClick={replaceAllBooks}>替换所有</Button>
              <Button color="gold" variant="solid" onClick={appendToEnd}>尾部追加</Button>
              <Button color="green" variant="solid" onClick={stepInsert}>步步插入</Button>
              <Button color="blue" variant="solid" onClick={insertToMiddle}>中间插入</Button>
              <Button color="orange" variant="solid" onClick={partialUpdate}>局部更新</Button>
            </Space>
          </Form.Item>
          <Form.Item label="性能测试操作" className="p-2">
            <Space wrap>
            <Button
            type={keyType === 'id' ? 'primary' : 'default'}
            onClick={() => handleToggleType('id')}
          >
            ID作为Key
          </Button>
          <Button
            type={keyType === 'index' ? 'primary' : 'default'}
            onClick={() => handleToggleType('index')}
          >
            Index作为Key
          </Button>
          <Button
            type={keyType === 'none' ? 'primary' : 'default'}
            onClick={() => handleToggleType('none')}
          >
            无Key
          </Button>
              <Button color="gold" variant="solid" onClick={autoTestReuse}>自动测试复用（单次）</Button>
              <Button color="green" variant="solid" onClick={autoTestBatchAndExportExcel} loading={loading}>批量测试并导出Excel</Button>
              <Button color="blue" variant="solid" onClick={exportReuseStatsToExcel}>导出Excel（当前）</Button>
            </Space>
          </Form.Item>
        </Form>
      </div>

      <div className="performance-metrics" style={{ margin: '10px 0', padding: '10px', background: '#f8f9fa', borderRadius: '4px' }}>
        <h3 style={{ margin: '0 0 10px 0', color: '#409EFF' }}>性能指标</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '10px' }}>
          <div className="metric-item">
            <span className="metric-label">渲染时间：</span>
            <span className="metric-value" style={{ color: '#e67e22', fontWeight: 'bold' }}>{renderTime || '0'} ms</span>
          </div>
          <div className="metric-item">
            <span className="metric-label">DOM创建数：</span>
            <span className="metric-value" style={{ color: '#409EFF' }}>{domTrackStats.created || 0}</span>
          </div>
          <div className="metric-item">
            <span className="metric-label">DOM复用数：</span>
            <span className="metric-value" style={{ color: '#67C23A' }}>{domTrackStats.reused || 0}</span>
          </div>
          <div className="metric-item">
            <span className="metric-label">DOM销毁数：</span>
            <span className="metric-value" style={{ color: '#F56C6C' }}>{domTrackStats.destroyed || 0}</span>
          </div>
          <div className="metric-item">
            <span className="metric-label">DOM复用率：</span>
            <span className="metric-value" style={{ color: '#909399', fontWeight: 'bold' }}>{reuseRate}%</span>
          </div>
        </div>
      </div>
      {renderTime && (
        <div style={{ marginBottom: '12px', color: '#e67e22', fontWeight: 'bold' }}>
          本次渲染耗时：{renderTime} ms<br />
          节点创建：{domTrackStats.created}，复用：{domTrackStats.reused}，销毁：{domTrackStats.destroyed}，复用率：{reuseRate}%
        </div>
      )}

      <div className="book-operations-display" style={{ margin: '20px 0', border: '1px solid #DCDFE6', padding: '15px', borderRadius: '4px' }}>
        <h3>图书数据预览 ({books.length} 条)</h3>
        <div style={{ maxHeight: '200px', overflowY: 'auto', border: '1px solid #EBEEF5', padding: '10px', marginTop: '10px' }}>
          {books.length > 0 ? (
            books.map(book => (
              <span key={book.id} style={{ display: 'inline-block', padding: '5px', margin: '3px', backgroundColor: '#ECF5FF', borderRadius: '3px', fontSize: '12px' }}>
                {book.title}
              </span>
            ))
          ) : (
            <p style={{ color: '#909399' }}>暂无图书数据，请点击上方按钮生成。</p>
          )}
        </div>
      </div>

      {showAcademicTestList && (
        <div className="academic-test-list">
          {academicBooks.map((book, $index) => (
            <span
              key={keyType === 'id' ? book.id : $index}
              ref={
                (el) => {
                  if (!refs.current[$index] && el) globalDOMTrackStats.created++;
                  else if (!el) globalDOMTrackStats.destroyed++;
            
                  refs.current[$index] = el;
                }
                
              } 
              data-id={book.id}
              style={{ padding: '5px', border: '1px solid #eee', margin: '2px', display: 'inline-block' }}
            >
              {book.title}
            </span>
          ))}
        </div>
      )}

      {categoryTree.length > 0 ? (
        <div className="tree-container">
          <div className="tree-operations">
            <p className="operation-hint">
              <InfoCircleOutlined /> 可以拖拽分类进行排序，点击按钮进行编辑操作
            </p>
          </div>
          <div className="tree-list">
            {categoryTree.map(category => (
              <CategoryItem key={category.id} category={category} />
            ))}
          </div>
        </div>
      ) : (
        <div className="empty-state">
          <div className="empty-icon">
            <FolderOpenOutlined />
          </div>
          <h3>暂无分类</h3>
          <p>当前没有图书分类，点击"重置数据"开始创建分类结构</p>
          <Button
            type="primary"
            onClick={resetCategories}
            loading={loading}>
            初始化分类
          </Button>
        </div>
      )}

      <Modal
        title={editingCategory ? '编辑分类' : '添加分类'}
        visible={editDialogVisible}
        onCancel={() => { setEditDialogVisible(false); setEditingCategory(null); }}
        footer={[
          <Button key="back" onClick={() => { setEditDialogVisible(false); setEditingCategory(null); }}>
            取 消
          </Button>,
          <Button key="submit" type="primary" onClick={saveCategory}>
            确 定
          </Button>,
        ]}
      >
        <Form layout="horizontal" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
          <Form.Item label="分类名称">
            <Input
              value={currentCategory.name || ''}
              onChange={(e) => setCurrentCategory(prev => ({ ...prev, name: e.target.value }))}
            />
          </Form.Item>
          <Form.Item label="图书数量">
            <InputNumber
              min={0}
              value={currentCategory.bookCount || 0}
              onChange={(value) => setCurrentCategory(prev => ({ ...prev, bookCount: value }))}
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item label="分类描述">
            <Input.TextArea
              value={currentCategory.description || ''}
              onChange={(e) => setCurrentCategory(prev => ({ ...prev, description: e.target.value }))}
            />
          </Form.Item>
          <Form.Item label="状态">
            <Select
              value={currentCategory.status || 'active'}
              onChange={(value) => setCurrentCategory(prev => ({ ...prev, status: value }))}
            >
              <Select.Option value="active">活跃</Select.Option>
              <Select.Option value="disabled">禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default NestedList;